#ifndef __UI_CONTROLLER__
#define __UI_CONTROLLER__

#include <QObject>
#include <QThread>
#include <QSerialPort>
#include <QMutex>

class Coordinator;
class QTimer;
class QTextCodec;

class UIController_Worker : public QObject
{
	Q_OBJECT

public:

	struct SerialConfig {
		QString port;
		uint32_t baud = QSerialPort::Baud115200;
		QSerialPort::DataBits data_bits = QSerialPort::Data8;
		QSerialPort::StopBits stop_bits = QSerialPort::OneStop;
		QSerialPort::Parity parity = QSerialPort::NoParity;
	};
	typedef struct SerialConfig SerialConfig;

    UIController_Worker(QObject *parent = nullptr);
    ~UIController_Worker();

    void setSerialParam(SerialConfig param);

signals:

	void scrn_switched(uint32_t scrn_id);
	void btn_clicked(uint32_t widget_id);
	void txt_changed(uint32_t widget_id, QString s);
	void sel_changed(uint32_t widget_id, uint32_t val);
	void tab_sel_changed(uint32_t widget_id, uint32_t line);

public slots:

	void start_work();
	void stop_work();

    void set_screen(uint32_t scrn_id);
    void set_btn_status(uint32_t widget_id, uint32_t pressed);
    void set_text(uint32_t widget_id, QString s);
    void set_icon(uint32_t widget_id, uint32_t icon_idx);
    void set_select(uint32_t widget_id, uint32_t val);
    void set_enable(uint32_t widget_id, bool enable);
    void set_table_data(uint32_t widget_id, QStringList s);
    void set_visible(uint32_t widget_id, bool visible);

private slots:

	void receive_data();
	void transfer_data(QByteArray data);

private:

    QByteArray rcsv_analyze(QByteArray &raw_data);
	void parse_msg(QByteArray msg);

private:

	QMutex m_mutex;

	SerialConfig m_param;
	QSerialPort *m_port;
	QTimer *m_read_timer;
	QTextCodec *m_gb_codec;				// display controller received only GB18030
										// use it to convert from/to UTF8

	QByteArray m_data;
};

class UIController : public QObject
{
	Q_OBJECT

public:

    UIController(QObject *parent = nullptr);
    ~UIController();

    UIController_Worker *getWorker() {
        return m_worker;
    }

signals:

	void start();
	void stop();

private:

	QThread m_worker_thread;
	UIController_Worker *m_worker;

    Coordinator *m_coordinator;
};

#endif
